package com.yupi.springbootinit.controller;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.rholder.retry.*;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.bizmq.BiMessageProducer;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.constant.FileConstant;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.manager.RedisLimiterManager;
import com.yupi.springbootinit.model.dto.chart.*;
import com.yupi.springbootinit.model.dto.file.UploadFileRequest;
import com.yupi.springbootinit.model.dto.post.PostQueryRequest;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.entity.Post;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.FileUploadBizEnum;
import com.yupi.springbootinit.model.vo.BiResponse;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.yupi.springbootinit.utils.ExcelUtils;
import com.yupi.springbootinit.utils.JsonUtils;
import com.yupi.springbootinit.utils.SqlUtils;
import com.yupi.springbootinit.ws.ChatEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.concurrent.*;

import static java.lang.Thread.sleep;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private AiManager aiManager;

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private BiMessageProducer biMessageProducer;


    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addchart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newchartId = chart.getId();
        return ResultUtils.success(newchartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletechart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldchart = chartService.getById(id);
        ThrowUtils.throwIf(oldchart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldchart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatechart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        Long id=chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldchart = chartService.getById(id);
        ThrowUtils.throwIf(oldchart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getchartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param chartQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Chart>> listchartByPage(@RequestBody ChartQueryRequest chartQueryRequest) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

//    /**
//     * 分页获取列表（封装类）
//     *
//     * @param chartQueryRequest
//     * @param request
//     * @return
//     */
//    @PostMapping("/list/page/vo")
//    public BaseResponse<Page<Chart>> listchartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
//            HttpServletRequest request) {
//        long current = chartQueryRequest.getCurrent();
//        long size = chartQueryRequest.getPageSize();
//        // 限制爬虫
//        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
//        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
//                getQueryWrapper(chartQueryRequest));
//        return ResultUtils.success(chartPage);
//    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<Chart>> listMychartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
            HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editchart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);

        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldchart = chartService.getById(id);
        ThrowUtils.throwIf(oldchart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldchart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    public QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }

        Long id = chartQueryRequest.getId();
        String goal = chartQueryRequest.getGoal();
        String chartType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();
        String name=chartQueryRequest.getName();

        queryWrapper.eq(id!=null&&id>0,"id",id);
        queryWrapper.eq(StringUtils.isNotBlank(name),"name",name);
        queryWrapper.eq(StringUtils.isNotBlank(goal),"goal",goal);
        queryWrapper.eq(StringUtils.isNotBlank(chartType),"chartType",chartType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete",false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 智能分析
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen")
    public BaseResponse<BiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        String name=genChartByAiRequest.getName();
        String goal=genChartByAiRequest.getGoal();
        String chartType=genChartByAiRequest.getChartType();
        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal),ErrorCode.PARAMS_ERROR,"目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name)&&name.length()>100,ErrorCode.PARAMS_ERROR,"名称过长");
        //校验文件
        long size=multipartFile.getSize();
        String originalFilename=multipartFile.getOriginalFilename();
        final long ONE_MB=1024*1024;
        ThrowUtils.throwIf(size>ONE_MB,ErrorCode.PARAMS_ERROR,"文件超过1mb");
        //校验文件后缀
        String suffix=FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList= Arrays.asList("png","jpg","webp","jpeg","xlsx");
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix),ErrorCode.PARAMS_ERROR,"文件后缀非法");

        User loginUser=userService.getLoginUser(request);
        //令桶限流
        redisLimiterManager.doRateLimit("genChartByAi_"+loginUser.getId());
        //用户输入
        StringBuilder userInput=new StringBuilder();
        userInput.append("分析需求：").append("\n");
        String useGoal=goal;
        if(StringUtils.isNotBlank(chartType)){
            useGoal+="，请使用"+chartType;
        }
        userInput.append(useGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        String csvData=ExcelUtils.excelToCsv(multipartFile);
        userInput.append(csvData).append("\n");
        Long biModelId=1799479915975483393L;

        Chart chart=new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setStatus("wait");
        chart.setUserId(loginUser.getId());
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save,ErrorCode.SYSTEM_ERROR,"图表保存失败");

        //todo 任务队列满了后抛异常
        Chart updateChart=new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus("running");
        boolean b=chartService.updateById(updateChart);
        if(!b){
            handleChartUpdateError(chart.getId(),"图表状态更改失败");
        }
        //调用ai
        String result=aiManager.doChat(biModelId,userInput.toString());
        String[] splits=result.split("【【【");
        if(splits.length<3){
            handleChartUpdateError(chart.getId(),"AI生成失败");
        }
        String genChart=splits[1];
        String genResult=splits[2];
        Chart updateChartTwice=new Chart();
        updateChartTwice.setId(chart.getId());
        updateChartTwice.setGenChart(genChart);
        //判断genResult是否是json数据
        if(!JsonUtils.isJson(genChart)){
            handleChartUpdateError(chart.getId(),"AI生成失败");
            updateChartTwice.setGenResult("null");
            updateChartTwice.setGenChart("null");
            updateChartTwice.setStatus("failed");
        }
        updateChartTwice.setGenResult(genResult);
        //todo 状态枚举
        updateChartTwice.setStatus("succeed");
        boolean b1=chartService.updateById(updateChartTwice);
        if(!b1){
            handleChartUpdateError(chart.getId(),"更新图表成功状态失败");
        }

        BiResponse biResponse=new BiResponse();
        biResponse.setGenChartId(chart.getId());
        biResponse.setGenChart(genChart);
        biResponse.setGenResult(genResult);
        return ResultUtils.success(biResponse);
    }

    /**
     * 智能分析
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async")
    public BaseResponse<BiResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile,
                                             GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        String name=genChartByAiRequest.getName();
        String goal=genChartByAiRequest.getGoal();
        String chartType=genChartByAiRequest.getChartType();
        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal),ErrorCode.PARAMS_ERROR,"目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name)&&name.length()>100,ErrorCode.PARAMS_ERROR,"名称过长");
        //校验文件
        long size=multipartFile.getSize();
        String originalFilename=multipartFile.getOriginalFilename();
        final long ONE_MB=1024*1024;
        ThrowUtils.throwIf(size>ONE_MB,ErrorCode.PARAMS_ERROR,"文件超过1mb");
        //校验文件后缀
        String suffix=FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList= Arrays.asList("png","jpg","webp","jpeg","xlsx");
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix),ErrorCode.PARAMS_ERROR,"文件后缀非法");

        User loginUser=userService.getLoginUser(request);
        //令桶限流
        redisLimiterManager.doRateLimit("genChartByAi_"+loginUser.getId());
        //用户输入
        StringBuilder userInput=new StringBuilder();
        userInput.append("分析需求：").append("\n");
        String useGoal=goal;
        if(StringUtils.isNotBlank(chartType)){
            useGoal+="，请使用"+chartType;
        }
        userInput.append(useGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        String csvData=ExcelUtils.excelToCsv(multipartFile);
        userInput.append(csvData).append("\n");
        Long biModelId=1799479915975483393L;

        Chart chart=new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setStatus("wait");
        chart.setUserId(loginUser.getId());
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save,ErrorCode.SYSTEM_ERROR,"图表保存失败");

        //todo 任务队列满了后抛异常
        CompletableFuture.runAsync(()->{
            //先修改图表任务状态
            Chart updateChart=new Chart();
            updateChart.setId(chart.getId());
            updateChart.setStatus("running");
            boolean b=chartService.updateById(updateChart);
            if(!b){
                handleChartUpdateError(chart.getId(),"图表状态更改失败");
            }
            //调用ai
            Callable<String> callable = () -> aiManager.doChat(biModelId, userInput.toString()); // 业务逻辑封装

            try {
                sleep(6000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            Predicate<String> resultPredicate = this::isgenc;
            Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
                    .retryIfResult(resultPredicate) // 结果为空则重试
                    .retryIfExceptionOfType(IOException.class) // IO异常重试
                    .retryIfRuntimeException() // 运行时异常重试
                    .withWaitStrategy(WaitStrategies.incrementingWait(10, TimeUnit.SECONDS, 10, TimeUnit.SECONDS)) // 递增等待策略
                    .withStopStrategy(StopStrategies.stopAfterAttempt(4)) // 最多尝试4次
                    .build();

            String result = null;
            try {
                result = retryer.call(callable);
                // 检查结果是否满足后续处理的条件，避免不必要的错误
            } catch (RetryException | ExecutionException e) {
                // 更具体的错误处理逻辑，如日志记录、通知等
                log.error("AI聊天重试失败或执行异常", e);
                // 可能还需要调用handleChartUpdateError或相应处理
            }
            String[] splits=result.split("【【【");
            if(splits.length<3){
                handleChartUpdateError(chart.getId(),"AI生成失败");
            }
            String genChart=splits[1];
            String genResult=splits[2];
            Chart updateChartTwice=new Chart();
            updateChartTwice.setId(chart.getId());
            updateChartTwice.setGenChart(genChart);
            updateChartTwice.setGenResult(genResult);
            updateChartTwice.setStatus("succeed");
            boolean b1=chartService.updateById(updateChartTwice);
            if(!b1){
                handleChartUpdateError(chart.getId(),"更新图表成功状态失败");
                return;
            }
        },threadPoolExecutor);

        BiResponse biResponse=new BiResponse();
        biResponse.setGenChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }

    public boolean isgenc(String result){
        if (result == null || !result.contains("【【【")) {
           return false;
        }

        String[] splits = result.split("【【【");
        if (splits.length < 3) {
            return false;
        }
        return true;
    }
    /**
     * 智能分析（异步消息队列
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async/mq")
    public BaseResponse<BiResponse> genChartByAiAsyncMq(@RequestPart("file") MultipartFile multipartFile,
                                                      GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        String name=genChartByAiRequest.getName();
        String goal=genChartByAiRequest.getGoal();
        String chartType=genChartByAiRequest.getChartType();
        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal),ErrorCode.PARAMS_ERROR,"目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name)&&name.length()>100,ErrorCode.PARAMS_ERROR,"名称过长");
        //校验文件
        long size=multipartFile.getSize();
        String originalFilename=multipartFile.getOriginalFilename();
        final long ONE_MB=1024*1024;
        ThrowUtils.throwIf(size>ONE_MB,ErrorCode.PARAMS_ERROR,"文件超过1mb");
        //校验文件后缀
        String suffix=FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList= Arrays.asList("png","jpg","webp","jpeg","xlsx");
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix),ErrorCode.PARAMS_ERROR,"文件后缀非法");

        User loginUser=userService.getLoginUser(request);
        //令桶限流
        redisLimiterManager.doRateLimit("genChartByAi_"+loginUser.getId());
        //用户输入
        StringBuilder userInput=new StringBuilder();
        userInput.append("分析需求：").append("\n");
        String useGoal=goal;
        if(StringUtils.isNotBlank(chartType)){
            useGoal+="，请使用"+chartType;
        }
        userInput.append(useGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        String csvData=ExcelUtils.excelToCsv(multipartFile);
        userInput.append(csvData).append("\n");
        Long biModelId=1799479915975483393L;

        Chart chart=new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setStatus("wait");
        chart.setUserId(loginUser.getId());
        boolean save = chartService.save(chart);
        ThrowUtils.throwIf(!save,ErrorCode.SYSTEM_ERROR,"图表保存失败");
        long newChartId=chart.getId();

        //todo 任务队列满了后抛异常
        biMessageProducer.sendMessage(String.valueOf(newChartId));

        BiResponse biResponse=new BiResponse();
        biResponse.setGenChartId(newChartId);
        return ResultUtils.success(biResponse);
    }


    private void handleChartUpdateError(long chartId,String execMessage){
        Chart updateChartResult=new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus("failed");
        updateChartResult.setExecMessage(execMessage);
        boolean updateResult=chartService.updateById(updateChartResult);
        if(!updateResult){
            log.error("更图表失败状态失败"+chartId);
        }
    }

}
